<?php

namespace addons\wanlshop\library\WanlPay;

use app\api\model\wanlshop\Order;
use app\common\library\Auth;

use addons\wanlshop\library\WanlChat\WanlChat;

use app\common\model\User;
use app\common\model\user\Level;
use app\common\model\user\LevelOrder;
use app\common\model\user\PerkGrant;
use app\common\model\user\RegionLevel;
use think\Db;
use think\Exception;
use think\Request;

use fast\Http;
use fast\Random;

use WanlPay\Yansongda\Pay;
use WanlPay\Yansongda\Log;
use WanlPay\Supports\Str;

/**
 *
 * WanlPay 多终端支付
 * @author 深圳前海万联科技有限公司 <wanlshop@i36k.com>
 * @link http://www.wanlshop.com
 *
 * @careful 非FastAdmin购买授权，未经版权所有权人书面许可，不得自行复制到第三方系统使用、二次开发、分支、复制和商业使用！
 * @creationtime  2020年8月7日23:46:12
 * @lasttime 2021年9月27日00:48:32
 * @version V2.x https://pay.yansongda.cn/docs/v2/
 **/
class WanlPay
{
    private $type;
    private $method;
    private $code;

    public function __construct($type = '', $method = '', $code = '')
    {
        $auth = Auth::instance(); // 方式
        $this->wanlchat = new WanlChat();
        $this->type = $type;  // 类型
        $this->method = $method; // 方式
        $this->user_id = $auth->isLogin() ? $auth->id : 0; // 用户ID
        $this->request = \think\Request::instance();
        $this->code = $code; // 小程序code
    }

    /**
     * 支付
     */
    public function pay($order_id, $order_type)
    {
        if ($this->user_id == 0) {
            return ['code' => 10001, 'msg' => '用户ID不存在'];
        }
        //修改 lina start
        // 获取支付信息
        /*$pay = model('app\api\model\wanlshop\Pay')
            ->where('order_id', 'in', $order_id)
            ->where(['rebate' => $this->user_id, 'type' => $order_type == 'groups' ? 'groups' : 'goods'])
            ->select();*/
        $pay = model('app\api\model\wanlshop\Pay')
            ->where('order_id', 'in', $order_id)
            ->where(['user_id' => $this->user_id, 'type' => $order_type])
            ->select();
        //修改 lina start
        // 1.0.8 升级
        $price = 0; // 付款金额
        $order_no = []; // 订单号
        $pay_id = []; // 交易号
        foreach ($pay as $row) {
            $price = bcadd($price, $row['price'], 2); // 总价格
            $order_no[] = $row['order_no']; // 订单集
            $pay_id[] = $row['id']; // 交易集
        }
        // 第三方支付订单 1.0.8
        if ($this->type != 'balance') {
            $payOutTrade = model('app\api\model\wanlshop\PayOutTrade');
            $payOutTrade->out_trade_no = date('YmdHis') . rand(10000000, 99999999) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
            $payOutTrade->pay_id = $pay_id;
            $payOutTrade->order_id = $order_id;
            $payOutTrade->price = $price;
            $payOutTrade->save();
        }
        // 1.0.8升级 拼团订单
        if ($order_type == 'groups') {
            $title = '拼团订单-' . implode("_", $order_no);
            $model_order = model('app\api\model\wanlshop\groups\Order');
            $model_order_goods = model('app\api\model\wanlshop\groups\OrderGoods');
            $model_goods = model('app\api\model\wanlshop\groups\Goods');
        } else {
            $title = '商城订单-' . implode("_", $order_no);
            $model_order = model('app\api\model\wanlshop\Order');
            $model_order_goods = model('app\api\model\wanlshop\OrderGoods');
            $model_goods = model('app\api\model\wanlshop\Goods');
        }
        // 支付方式
        if ($this->type == 'balance') {
            // 支付列表
            $pay_list = [];
            // 订单列表
            $order_list = [];
            // 拼团列表
            $groups_list = [];
            // 拼团列表
            $groups_team_list = [];
            // 判断金额
            $user = model('app\common\model\User')->get($this->user_id);
            if (!$user || $user['money'] < $price) {
                return ['code' => 500, 'msg' => '余额不足本次支付'];
            }
            $result = false;
            $balance_no = date('YmdHis') . rand(10000000, 99999999);
            //新增 订单文案 lina start
            $order_type_text = "拼团";
            if ($order_type == "userlevel") {
                $order_type_text = "会员等级";
            }
            if ($order_type == "goods") {
                $order_type_text = "商品";
            }
            //新增 订单文案 lina start
            Db::startTrans();
            try {
                //新增 判断会员等级购买 lina start
                if ($order_type == "userlevel") {
                    $result = self::updateUserLevel($user['id'], $order_id);
                    // 支付列表
                    $pay_list[] = [
                        'id' => $pay[0]["id"],
                        'trade_no' => $balance_no, // 第三方交易号
                        'pay_type' => 0, // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                        'pay_state' => 1, // 支付状态 (支付回调):0=未支付,1=已支付,2=已退款
                        'total_amount' => $price, // 总金额
                        'actual_payment' => $pay[0]['price'], // 实际支付
                        'notice' => json_encode([
                            'type' => $this->type,
                            'user_id' => $user['id'],
                            'trade_no' => $balance_no,
                            'out_trade_no' => $pay[0]['pay_no'],
                            'amount' => $pay[0]['price'],
                            'total_amount' => $price,
                            'order_id' => $pay[0]['order_id'],
                            'trade_type' => 'BALANCE',
                            'version' => '1.0.0'
                        ])
                    ];
                    // 更新支付列表
                    $result = model('app\api\model\wanlshop\Pay')->saveAll($pay_list);
                } //新增 判断会员等级购买 lina end
                else {
                    foreach ($pay as $row) {
                        $isAlone = false; // 拼团订单一般是单订单，暂可以这样操作
                        $groups_state = 'start'; // 拼团状态
                        foreach ($model_order_goods->where('order_id', $row['order_id'])->select() as $goods) {
                            if ($order_type == 'groups' && !empty($goods['group_type'])) {
                                if ($goods['group_type'] == 'alone') {
                                    $isAlone = true;
                                } else {
                                    // 查询团ID
                                    $groups = model('app\api\model\wanlshop\groups\Groups')
                                        ->where(['group_no' => $goods['group_no']])
                                        ->find();
                                    // 判断是否超团
                                    $groups_team = model('app\api\model\wanlshop\groups\Team')
                                        ->where(['group_no' => $goods['group_no']])
                                        ->select();
                                    // 已拼团总数量
                                    $groups_team_count = count($groups_team);
                                    if ($groups_team_count >= $groups['people_num'] || $groups['join_num'] >= $groups['people_num']) {
                                        $this->error(__('参与拼单失败，拼团已完成'));
                                    }
                                    // 判断是否具备成团条件
                                    if (($groups['people_num'] - $groups_team_count) <= 1 || ($groups['people_num'] - $groups['join_num']) <= 1) {
                                        $groups_state = 'success';
                                        //调整其他拼团订单
                                        // 订单状态:1=待支付,2=待成团,3=待发货,4=待收货,5=待评论,6=已完成,7=已取消
                                        foreach ($groups_team as $team) {
                                            $order_list[] = ['id' => $team['order_id'], 'state' => 3, 'groupstime' => time()];
                                        }
                                    }
                                    // 拼团状态: ready=准备中,start=拼团中,success=已成团,fail=拼团失败,auto=自动成团
                                    $groups_list[] = [
                                        'id' => $groups['id'],
                                        'join_num' => $groups['join_num'] + 1,
                                        'state' => $groups_state,
                                        'grouptime' => $groups_state === 'success' ? time() : NULL
                                    ];
                                    $groups_team_list[] = [
                                        'user_id' => $user['id'],
                                        'shop_id' => $goods['shop_id'],
                                        'group_no' => $goods['group_no'],
                                        'order_id' => $goods['order_id'],
                                        'order_goods_id' => $goods['id']
                                    ];
                                }
                            }
                            // 新增付款人数、新增销量
                            $model_goods->where('id', $goods['goods_id'])->inc('payment')->inc('sales', $goods['number'])->update();
                        }
                        // 订单列表
                        if ($groups_state === 'success') {
                            $order_list[] = ['id' => $row['order_id'], 'state' => 3, 'paymenttime' => time(), 'groupstime' => time()];
                        } else {
                            $order_list[] = ['id' => $row['order_id'], 'state' => $isAlone ? 3 : 2, 'paymenttime' => time()];
                        }
                        // 支付列表
                        $pay_list[] = [
                            'id' => $row['id'],
                            'trade_no' => $balance_no, // 第三方交易号
                            'pay_type' => 0, // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                            'pay_state' => 1, // 支付状态 (支付回调):0=未支付,1=已支付,2=已退款
                            'total_amount' => $price, // 总金额
                            'actual_payment' => $row['price'], // 实际支付
                            'notice' => json_encode([
                                'type' => $this->type,
                                'user_id' => $user['id'],
                                'trade_no' => $balance_no,
                                'out_trade_no' => $row['pay_no'],
                                'amount' => $row['price'],
                                'total_amount' => $price,
                                'order_id' => $row['order_id'],
                                'trade_type' => 'BALANCE',
                                'version' => '1.0.0'
                            ])
                        ];
                    }
                    // 更新支付列表
                    $result = model('app\api\model\wanlshop\Pay')->saveAll($pay_list);
                    // 更新订单列表
                    $result = $model_order->saveAll($order_list);

                    //2023-10-31 lina 新增 start
                    //用户上级是团长
                    /*if(!empty($user["team_id"])){
                        $agent=\app\common\model\User::find($user["team_id"]);
                        dump($payList);die();
                        if(!empty($agent) && $agent["identity"]==1){
                            $agent_level=\app\common\model\team\Level::find($agent["team_id"]);
                            $money=bcmul($order["price"],(($agent_level["goods_rebate"]??10)/100),2);
                            $rebate_content=[
                                "team_level_details"=>json_encode($agent_level),
                                "team_level_id"=>$agent_level["id"],
                                "money"=>$money,
                            ];
                            $distribution_data=[
                                "type"=>2,
                                "order_no"=>$order["order_no"],
                                "agent_id"=>$user["agent_id"],
                                "identity"=>1,
                                "user_id"=>$user["id"],
                                "commiss_user_id"=>$user["id"],
                                "money"=>$money,
                                "rebate_content"=>$rebate_content,
                            ];
                            dump($distribution_data);die();
                            model('app\coomon\model\Distribution')->saveAll($distribution_data);//新增返利记录
                        }
                    }die();*/
                    $result = self::distribution($user['id'], $order_id);
                    //2023-10-31 lina 新增 end
                }
                // 修改用户金额
                if (count($order_no) == 1) {
                    $result = self::money(-$price, $user['id'], '余额支付' . $order_type_text . '订单', $order_type == 'groups' ? 'groups' : ($order_type == "userlevel" ?: 'pay'), implode(",", $order_no));
                } else {
                    $result = self::money(-$price, $user['id'], '余额合并支付' . $order_type_text . '订单', $order_type == 'groups' ? 'groups' : ($order_type == "userlevel" ?: 'pay'), implode(",", $order_no));
                }
                if ($order_type == 'groups') {
                    model('app\api\model\wanlshop\groups\Groups')->isUpdate()->saveAll($groups_list);
                    model('app\api\model\wanlshop\groups\Team')->saveAll($groups_team_list);
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['code' => 10002, 'msg' => $e->getMessage()];
            }
            // 返回结果
            if ($result !== false) {
                return ['code' => 200, 'msg' => '成功', 'data' => []];
            } else {
                return ['code' => 10003, 'msg' => '支付异常'];
            }
            // 支付宝支付、更新数据均在回调中执行
        } else if ($this->type == 'alipay') {
            $data = [
                'out_trade_no' => $payOutTrade->out_trade_no,
                'total_amount' => $price,
                'subject' => $title
            ];
            try {
                $alipay = Pay::alipay(self::getConfig($this->type))->{$this->method}($data);
                if ($this->method == 'app' || $this->method == 'wap') {
                    return ['code' => 200, 'msg' => '成功', 'data' => $alipay->getContent()];
                } else {
                    return ['code' => 200, 'msg' => '成功', 'data' => $alipay];
                }
            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];

            }
            // 微信支付
        } else if ($this->type == 'wechat') {
            $data = [
                'out_trade_no' => $payOutTrade->out_trade_no, // 订单号
                'body' => $title, // 标题
                'total_fee' => $price * 100 //付款金额 单位分
            ];
            if ($this->method == 'miniapp') {
                // 获取微信openid，前期版本仅可安全获取，后续版本优化登录逻辑
                $config = get_addon_config('wanlshop');
                $params = [
                    'appid' => $config['mp_weixin']['appid'],
                    'secret' => $config['mp_weixin']['appsecret'],
                    'js_code' => $this->code,
                    'grant_type' => 'authorization_code'
                ];
                $time = time();
                $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
                if ($result['ret']) {
                    $json = (array)json_decode($result['msg'], true);
                    $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'openid' => $json['openid']]);
                    if (!$third) {
                        $third = model('app\api\model\wanlshop\Third');
                        // array_key_exists("unionid",$json)
                        if (isset($json['unionid'])) {
                            $third->unionid = $json['unionid'];
                            $third->openid = $json['openid'];
                        } else {
                            $third->openid = $json['openid'];
                        }
                        $third->access_token = $json['session_key'];
                        $third->expires_in = 7776000;
                        $third->logintime = $time;
                        $third->expiretime = $time + 7776000;
                        $third->user_id = $this->user_id;
                        $third->save();
                    }
                    $data['openid'] = $json['openid'];
                } else {
                    return ['code' => 10005, 'msg' => '获取微信openid失败，无法支付'];
                }
            } else if ($this->method == 'mp') {
                // 微信公众平台支付必有OPENID 1.1.2升级
                $third = model('app\api\model\wanlshop\Third')
                    ->where(['platform' => 'weixin_h5', 'user_id' => $this->user_id])
                    ->find();
                if ($third) {
                    $data['openid'] = $third['openid'];
                } else {
                    return ['code' => 10005, 'msg' => '获取微信openid失败，无法支付'];
                }
            }
            // 开始支付
            try {
                $wechat = Pay::wechat(self::getConfig($this->type))->{$this->method}($data);
                if ($this->method == 'app') {
                    return ['code' => 200, 'msg' => '成功', 'data' => $wechat->getContent()];
                } else if ($this->method == 'wap') {
                    return ['code' => 200, 'msg' => '成功', 'data' => $wechat->getTargetUrl()];
                } else {
                    return ['code' => 200, 'msg' => '成功', 'data' => $wechat];
                }
            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];
            }
            // 百度支付
        } else if ($this->type == 'baidu') {
            try {

            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];
            }
            // QQ支付
        } else if ($this->type == 'qq') {
            try {

            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];
            }
            // 苹果支付
        } else if ($this->type == 'apple') {
            try {

            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];
            }
        } else {
            return ['code' => 10010, 'msg' => '未找到任何有效支付'];
        }
    }

    /**
     * 用户充值
     */
    public function recharge($price)
    {
        if ($this->user_id == 0) {
            return ['code' => 10001, 'msg' => '用户ID不存在'];
        }
        if ($price <= 0) {
            return ['code' => 10002, 'msg' => '充值金额不合法'];
        }
        // 充值订单号
        $pay_no = date("Ymdhis") . sprintf("%08d", $this->user_id) . mt_rand(1000, 9999);
        // 支付标题
        $title = '充值-' . $pay_no;
        // 生成一个订单
        $order = \app\api\model\wanlshop\RechargeOrder::create([
            'orderid' => $pay_no,
            'user_id' => $this->user_id,
            'amount' => $price,
            'payamount' => 0,
            'paytype' => $this->type,
            'ip' => $this->request->ip(),
            'useragent' => substr($this->request->server('HTTP_USER_AGENT'), 0, 255),
            'status' => 'created'
        ]);

        if ($this->type == 'alipay') {
            // 获取配置
            $payConfig = self::getConfig($this->type);
            $payConfig['notify_url'] = str_replace("notify", "notify_recharge", $payConfig['notify_url']);
            $data = [
                'out_trade_no' => $pay_no,
                'total_amount' => $price,
                'subject' => $title
            ];
            try {
                $alipay = Pay::alipay($payConfig)->{$this->method}($data);
                if ($this->method == 'app' || $this->method == 'wap') {
                    return ['code' => 200, 'msg' => '成功', 'data' => $alipay->getContent()];
                } else {
                    return ['code' => 200, 'msg' => '成功', 'data' => $alipay];
                }
                // 1.1.5升级 捕获异常
            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];
            }

            // 微信支付
        } else if ($this->type == 'wechat') {
            // 获取配置
            $payConfig = self::getConfig($this->type);
            $payConfig['notify_url'] = str_replace("notify", "notify_recharge", $payConfig['notify_url']);
            $data = [
                'out_trade_no' => $pay_no, // 订单号
                'body' => $title, // 标题
                'total_fee' => $price * 100 //付款金额 单位分
            ];
            if ($this->method == 'miniapp') {
                // 获取微信openid，前期版本仅可安全获取，后续版本优化登录逻辑
                $config = get_addon_config('wanlshop');
                $params = [
                    'appid' => $config['mp_weixin']['appid'],
                    'secret' => $config['mp_weixin']['appsecret'],
                    'js_code' => $this->code,
                    'grant_type' => 'authorization_code'
                ];
                $time = time();
                $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
                if ($result['ret']) {
                    $json = (array)json_decode($result['msg'], true);
                    $third = model('app\api\model\wanlshop\Third')->get(['platform' => 'weixin_open', 'openid' => $json['openid']]);
                    if (!$third) {
                        $third = model('app\api\model\wanlshop\Third');
                        if (isset($json['unionid'])) {
                            $third->unionid = $json['unionid'];
                            $third->openid = $json['openid'];
                        } else {
                            $third->openid = $json['openid'];
                        }
                        $third->access_token = $json['session_key'];
                        $third->expires_in = 7776000;
                        $third->logintime = $time;
                        $third->expiretime = $time + 7776000;
                        $third->user_id = $this->user_id;
                        $third->save();
                    }
                    $data['openid'] = $json['openid'];
                } else {
                    return ['code' => 10005, 'msg' => '获取微信openid失败，无法支付'];
                }
            } else if ($this->method == 'mp') {
                // 微信公众平台支付必有OPENID 1.1.2升级
                $third = model('app\api\model\wanlshop\Third')
                    ->where(['platform' => 'weixin_h5', 'user_id' => $this->user_id])
                    ->find();
                if ($third) {
                    $data['openid'] = $third['openid'];
                } else {
                    return ['code' => 10005, 'msg' => '获取微信openid失败，无法支付'];
                }
            }
            // 开始支付
            try {
                $wechat = Pay::wechat($payConfig)->{$this->method}($data);
                if ($this->method == 'app') {
                    return ['code' => 200, 'msg' => '成功', 'data' => $wechat->getContent()];
                } else if ($this->method == 'wap') {
                    return ['code' => 200, 'msg' => '成功', 'data' => $wechat->getTargetUrl()];
                } else {
                    return ['code' => 200, 'msg' => '成功', 'data' => $wechat];
                }
                // 1.1.5升级 捕获异常
            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];
            }
            // 百度支付
        } else if ($this->type == 'baidu') {
            try {

            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];
            }
            // QQ支付
        } else if ($this->type == 'qq') {
            try {

            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];
            }
            // 苹果支付
        } else if ($this->type == 'apple') {
            try {

            } catch (\Exception $e) {
                return ['code' => 10006, 'msg' => $this->type . '：' . $e->getMessage()];
            }
        } else {
            return ['code' => 10010, 'msg' => '未找到任何有效支付'];
        }
    }

    /**
     * 支付回调
     */
    public function notify()
    {
        $wanlpay = Pay::{$this->type}(self::getConfig($this->type));
        try {
            $result = $wanlpay->verify();
            Log::debug('Wanlpay notify all', $result->all());
            /*$xml="<xml><appid><![CDATA[wx0001d6240b1bd5a5]]></appid>\n<bank_type><![CDATA[OTHERS]]></bank_type>\n<cash_fee><![CDATA[10]]></cash_fee>\n<fee_type><![CDATA[CNY]]></fee_type>\n<is_subscribe><![CDATA[N]]></is_subscribe>\n<mch_id><![CDATA[1658135637]]></mch_id>\n<nonce_str><![CDATA[k30hOspBF6o8uQpw]]></nonce_str>\n<openid><![CDATA[oCYCw61jeH2gTyM7QkGsNnF_kzsM]]></openid>\n<out_trade_no><![CDATA[202311131548045028201252100101]]></out_trade_no>\n<result_code><![CDATA[SUCCESS]]></result_code>\n<return_code><![CDATA[SUCCESS]]></return_code>\n<sign><![CDATA[673085B46FFC594B8EB05F5547EB4566]]></sign>\n<time_end><![CDATA[20231113154810]]></time_end>\n<total_fee>10</total_fee>\n<trade_type><![CDATA[JSAPI]]></trade_type>\n<transaction_id><![CDATA[4200002039202311134665998477]]></transaction_id>\n</xml>";
            //将XML转为array
            $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);*/
            // 查询支付集
            $payOutTrade = model('app\api\model\wanlshop\PayOutTrade')
                ->where(['out_trade_no' => $result['out_trade_no']])
                ->find();

            // 查询订单是否存在
            $pay = model('app\api\model\wanlshop\Pay')
                ->where('id', 'in', $payOutTrade['pay_id'])
                ->where('pay_state', 'neq', '1')
                ->select();
            if (!$pay) {
                return ['code' => 10001, 'msg' => '网络异常'];
            }
            // 1.0.8升级 拼团订单
            $order_type = $pay[0]['type'];
            if ($order_type == 'groups') {
                $model_order = model('app\api\model\wanlshop\groups\Order');
                $model_order_goods = model('app\api\model\wanlshop\groups\OrderGoods');
                $model_goods = model('app\api\model\wanlshop\groups\Goods');
            } else {
                $model_order = model('app\api\model\wanlshop\Order');
                $model_order_goods = model('app\api\model\wanlshop\OrderGoods');
                $model_goods = model('app\api\model\wanlshop\Goods');
            }
            $trade_no = '';
            // 支付类型
            $pay_type = 8;
            $user_id = 0;
            $order_no = [];
            // 总价格
            $price = 0;

            // 主要用于日志
            foreach ($pay as $row) {
                // $price += $row['price']; 1.0.8 升级
                $price = bcadd($price, $row['price'], 2); // 总价格
                // 订单集
                $order_no[] = $row['order_no'];
                $user_id = $row['user_id'];
            }
            // -----------------------------判断订单是否合法-----------------------------
            $config = get_addon_config('wanlshop');
            // 支付宝
            if ($this->type == 'alipay') {
                // 判断状态
                if (in_array($result['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                    // 判断金额
                    if ($price != $result['total_amount']) {
                        return ['code' => 10002, 'msg' => '支付金额不合法'];
                    }
                    // 判断appid
                    if ($config['sdk_alipay']['app_id'] != $result['app_id']) {
                        return ['code' => 10003, 'msg' => 'APPID不合法'];
                    }
                } else {
                    return ['code' => 500, 'msg' => '支付回调失败'];
                }
                // 回调支付
                $pay_type = 2; // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                $pay_name = '支付宝';
                $trade_no = $result['trade_no'];
            } else if ($this->type == 'wechat') {
                // 判断状态
                if ($result['result_code'] == 'SUCCESS') {
                    // 判断金额
                    if ($price != ($result['total_fee'] / 100)) {
                        return ['code' => 10002, 'msg' => '支付金额不合法'];
                    }
                    // 判断商家ID
                    if ($config['sdk_qq']['mch_id'] != $result['mch_id']) {
                        return ['code' => 10004, 'msg' => '商户不合法'];
                    }
                    // H5微信支付
                    if ($result['trade_type'] == 'MWEB') {
                        if ($config['sdk_qq']['gz_appid'] != $result['appid']) {
                            return ['code' => 10005, 'msg' => '支付类型 ' . $result['trade_type'] . ' 不合法'];
                        }
                    }
                    // 小程序支付
                    if ($result['trade_type'] == 'JSAPI') {
                        if ($config['mp_weixin']['appid'] != $result['appid']) {
                            if ($config['sdk_qq']['gz_appid'] != $result['appid']) {
                                return ['code' => 10006, 'msg' => '支付APPID不合法'];
                            }
                        }
                    }
                    // App支付
                    if ($result['trade_type'] == 'APP') {
                        if ($config['sdk_qq']['wx_appid'] != $result['appid']) {
                            return ['code' => 10007, 'msg' => '支付类型 ' . $result['trade_type'] . ' 不合法'];
                        }
                    }
                } else {
                    return ['code' => 500, 'msg' => '支付回调失败'];
                }
                // 回调支付
                $pay_type = 1; // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                $pay_name = '微信';
                $trade_no = $result['transaction_id'];
            }
            // -----------------------------支付成功，修改订单-----------------------------
            $order_list = [];
            $pay_list = [];
            // 拼团列表
            $groups_list = [];
            // 拼团列表
            $groups_team_list = [];
            //新增 判断会员等级购买 lina start
            if ($order_type == "userlevel") {
                $result = self::updateUserLevel($user_id, $pay[0]['order_id']);
                // 支付列表 1.0.9升级
                $pay_list[] = [
                    'id' => $pay[0]['id'],
                    'trade_no' => $trade_no, // 第三方交易号
                    'pay_type' => $pay_type, // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                    'pay_state' => 1, // 支付状态 (支付回调):0=未支付,1=已支付,2=已退款
                    'total_amount' => $price, // 总金额
                    'actual_payment' => $pay[0]['price'], // 实际支付
                    'notice' => json_encode($result)
                ];
                // 更新支付列表
                model('app\api\model\wanlshop\Pay')->saveAll($pay_list);
            } //新增 判断会员等级购买 lina end
            else {
                foreach ($pay as $row) {
                    $isAlone = false; // 拼团订单一般是单订单，暂可以这样操作
                    $groups_state = 'start'; // 拼团状态
                    foreach ($model_order_goods->where('order_id', $row['order_id'])->select() as $goods) {
                        if ($order_type == 'groups' && !empty($goods['group_type'])) {
                            if ($goods['group_type'] == 'alone') {
                                $isAlone = true;
                            } else {
                                // 查询团ID
                                $groups = model('app\api\model\wanlshop\groups\Groups')
                                    ->where(['group_no' => $goods['group_no']])
                                    ->find();
                                // 判断是否超团
                                $groups_team = model('app\api\model\wanlshop\groups\Team')
                                    ->where(['group_no' => $goods['group_no']])
                                    ->select();
                                // 已拼团总数量
                                $groups_team_count = count($groups_team);
                                if ($groups_team_count >= $groups['people_num'] || $groups['join_num'] >= $groups['people_num']) {
                                    $this->error(__('参与拼单失败，拼团已完成'));
                                }
                                // 判断是否具备成团条件
                                if (($groups['people_num'] - $groups_team_count) <= 1 || ($groups['people_num'] - $groups['join_num']) <= 1) {
                                    $groups_state = 'success';
                                    //调整其他拼团订单
                                    // 订单状态:1=待支付,2=待成团,3=待发货,4=待收货,5=待评论,6=已完成,7=已取消
                                    foreach ($groups_team as $team) {
                                        $order_list[] = ['id' => $team['order_id'], 'state' => 3, 'groupstime' => time()];
                                    }
                                }
                                // 拼团状态: ready=准备中,start=拼团中,success=已成团,fail=拼团失败,auto=自动成团
                                $groups_list[] = [
                                    'id' => $groups['id'],
                                    'join_num' => $groups['join_num'] + 1,
                                    'state' => $groups_state
                                ];
                                $groups_team_list[] = [
                                    'user_id' => $user_id, // 1.0.9升级
                                    'shop_id' => $goods['shop_id'],
                                    'group_no' => $goods['group_no'],
                                    'order_id' => $goods['order_id'],
                                    'order_goods_id' => $goods['id']
                                ];
                            }
                        }
                        // 新增付款人数、新增销量
                        $model_goods->where('id', $goods['goods_id'])->inc('payment')->inc('sales', $goods['number'])->update();
                    }
                    // 订单列表
                    if ($groups_state === 'success') {
                        $order_list[] = ['id' => $row['order_id'], 'state' => 3, 'paymenttime' => time(), 'groupstime' => time()];
                    } else {
                        $order_list[] = ['id' => $row['order_id'], 'state' => $isAlone ? 3 : 2, 'paymenttime' => time()];
                    }
                    // 支付列表 1.0.9升级
                    $pay_list[] = [
                        'id' => $row['id'],
                        'trade_no' => $trade_no, // 第三方交易号
                        'pay_type' => $pay_type, // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                        'pay_state' => 1, // 支付状态 (支付回调):0=未支付,1=已支付,2=已退款
                        'total_amount' => $price, // 总金额
                        'actual_payment' => $row['price'], // 实际支付
                        'notice' => json_encode($result)
                    ];
                }
                // 更新支付列表
                model('app\api\model\wanlshop\Pay')->saveAll($pay_list);
                // 更新订单列表
                $model_order->saveAll($order_list);
                //lina 新增 start
                $result = self::distribution($user_id, $pay[0]['order_id']);
                //lina 新增 end
            }
            //新增 判断会员等级购买 lina end
            // 支付日志
            model('app\common\model\MoneyLog')->create([
                'user_id' => $user_id,
                'money' => -$price, // 操作金额
                'memo' => $pay_name . '支付' . $order_type == 'groups' ? '拼团' : ($order_type == "userlevel" ? '会员卡' : '商城') . '订单', // 备注
                'type' => $order_type == 'groups' ? 'groups' : ($order_type == "userlevel" ? 'userlevel' : 'pay'), // 类型
                'service_ids' => implode(",", $order_no) // 业务ID
            ]);
            Log::debug('Wanlpay notify', $result->all());
            if ($order_type == 'groups') {
                model('app\api\model\wanlshop\groups\Groups')->isUpdate()->saveAll($groups_list);
                model('app\api\model\wanlshop\groups\Team')->saveAll($groups_team_list);
            }
            // 1.1.5升级 捕获异常
        } catch (\Exception $e) {
            return ['code' => 10008, 'msg' => $e->getMessage()];
        }
        // 返回给支付接口
        return ['code' => 200, 'msg' => $wanlpay->success()->send()];
    }

    /**
     * 支付回调
     */
    public function notify2()
    {
        $wanlpay = Pay::{$this->type}(self::getConfig($this->type));
        try {
            /* $result = $wanlpay->verify();
             Log::debug('Wanlpay notify all', $result->all());*/
            $xml = "<xml><appid><![CDATA[wx0001d6240b1bd5a5]]></appid>\n<bank_type><![CDATA[OTHERS]]></bank_type>\n<cash_fee><![CDATA[10]]></cash_fee>\n<fee_type><![CDATA[CNY]]></fee_type>\n<is_subscribe><![CDATA[N]]></is_subscribe>\n<mch_id><![CDATA[1658135637]]></mch_id>\n<nonce_str><![CDATA[x9PI4HrQcZnj5mQs]]></nonce_str>\n<openid><![CDATA[oCYCw61jeH2gTyM7QkGsNnF_kzsM]]></openid>\n<out_trade_no><![CDATA[202311131645229706911450100569]]></out_trade_no>\n<result_code><![CDATA[SUCCESS]]></result_code>\n<return_code><![CDATA[SUCCESS]]></return_code>\n<sign><![CDATA[948AE25D201412668FB14887510B2A40]]></sign>\n<time_end><![CDATA[20231113164547]]></time_end>\n<total_fee>10</total_fee>\n<trade_type><![CDATA[JSAPI]]></trade_type>\n<transaction_id><![CDATA[4200002037202311131624999401]]></transaction_id>\n</xml>";
            //将XML转为array
            $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            // 查询支付集
            $payOutTrade = model('app\api\model\wanlshop\PayOutTrade')
                ->where(['out_trade_no' => $result['out_trade_no']])
                ->find();
            // 查询订单是否存在
            $pay = model('app\api\model\wanlshop\Pay')
                ->where('id', 'in', $payOutTrade['pay_id'])->fetchSql()
                ->where('pay_state', 'neq', '1')
                ->select();

            if (!$pay) {
                return ['code' => 10001, 'msg' => '网络异常'];
            }
            // 1.0.8升级 拼团订单
            $order_type = $pay[0]['type'];
            if ($order_type == 'groups') {
                $model_order = model('app\api\model\wanlshop\groups\Order');
                $model_order_goods = model('app\api\model\wanlshop\groups\OrderGoods');
                $model_goods = model('app\api\model\wanlshop\groups\Goods');
            } else {
                $model_order = model('app\api\model\wanlshop\Order');
                $model_order_goods = model('app\api\model\wanlshop\OrderGoods');
                $model_goods = model('app\api\model\wanlshop\Goods');
            }
            $trade_no = '';
            // 支付类型
            $pay_type = 8;
            $user_id = 0;
            $order_no = [];
            // 总价格
            $price = 0;

            // 主要用于日志
            foreach ($pay as $row) {
                // $price += $row['price']; 1.0.8 升级
                $price = bcadd($price, $row['price'], 2); // 总价格
                // 订单集
                $order_no[] = $row['order_no'];
                $user_id = $row['user_id'];
            }
            // -----------------------------判断订单是否合法-----------------------------
            $config = get_addon_config('wanlshop');
            // 支付宝
            if ($this->type == 'alipay') {
                // 判断状态
                if (in_array($result['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                    // 判断金额
                    if ($price != $result['total_amount']) {
                        return ['code' => 10002, 'msg' => '支付金额不合法'];
                    }
                    // 判断appid
                    if ($config['sdk_alipay']['app_id'] != $result['app_id']) {
                        return ['code' => 10003, 'msg' => 'APPID不合法'];
                    }
                } else {
                    return ['code' => 500, 'msg' => '支付回调失败'];
                }
                // 回调支付
                $pay_type = 2; // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                $pay_name = '支付宝';
                $trade_no = $result['trade_no'];
            } else if ($this->type == 'wechat') {
                // 判断状态
                if ($result['result_code'] == 'SUCCESS') {
                    // 判断金额
                    if ($price != ($result['total_fee'] / 100)) {
                        return ['code' => 10002, 'msg' => '支付金额不合法'];
                    }
                    // 判断商家ID
                    if ($config['sdk_qq']['mch_id'] != $result['mch_id']) {
                        return ['code' => 10004, 'msg' => '商户不合法'];
                    }
                    // H5微信支付
                    if ($result['trade_type'] == 'MWEB') {
                        if ($config['sdk_qq']['gz_appid'] != $result['appid']) {
                            return ['code' => 10005, 'msg' => '支付类型 ' . $result['trade_type'] . ' 不合法'];
                        }
                    }
                    // 小程序支付
                    if ($result['trade_type'] == 'JSAPI') {
                        if ($config['mp_weixin']['appid'] != $result['appid']) {
                            if ($config['sdk_qq']['gz_appid'] != $result['appid']) {
                                return ['code' => 10006, 'msg' => '支付APPID不合法'];
                            }
                        }
                    }
                    // App支付
                    if ($result['trade_type'] == 'APP') {
                        if ($config['sdk_qq']['wx_appid'] != $result['appid']) {
                            return ['code' => 10007, 'msg' => '支付类型 ' . $result['trade_type'] . ' 不合法'];
                        }
                    }
                } else {
                    return ['code' => 500, 'msg' => '支付回调失败'];
                }
                // 回调支付
                $pay_type = 1; // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                $pay_name = '微信';
                $trade_no = $result['transaction_id'];
            }
            // -----------------------------支付成功，修改订单-----------------------------
            $order_list = [];
            $pay_list = [];
            // 拼团列表
            $groups_list = [];
            // 拼团列表
            $groups_team_list = [];
            //新增 判断会员等级购买 lina start
            if ($order_type == "userlevel") {
                $result = self::updateUserLevel($user_id, $pay[0]['order_id']);
                // 支付列表 1.0.9升级
                $pay_list[] = [
                    'id' => $pay[0]['order_id'],
                    'trade_no' => $trade_no, // 第三方交易号
                    'pay_type' => $pay_type, // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                    'pay_state' => 1, // 支付状态 (支付回调):0=未支付,1=已支付,2=已退款
                    'total_amount' => $price, // 总金额
                    'actual_payment' => $pay[0]['price'], // 实际支付
                    'notice' => json_encode($result)
                ];
                // 更新支付列表
                model('app\api\model\wanlshop\Pay')->saveAll($pay_list);
            } //新增 判断会员等级购买 lina end
            else {
                foreach ($pay as $row) {
                    $isAlone = false; // 拼团订单一般是单订单，暂可以这样操作
                    $groups_state = 'start'; // 拼团状态
                    foreach ($model_order_goods->where('order_id', $row['order_id'])->select() as $goods) {
                        if ($order_type == 'groups' && !empty($goods['group_type'])) {
                            if ($goods['group_type'] == 'alone') {
                                $isAlone = true;
                            } else {
                                // 查询团ID
                                $groups = model('app\api\model\wanlshop\groups\Groups')
                                    ->where(['group_no' => $goods['group_no']])
                                    ->find();
                                // 判断是否超团
                                $groups_team = model('app\api\model\wanlshop\groups\Team')
                                    ->where(['group_no' => $goods['group_no']])
                                    ->select();
                                // 已拼团总数量
                                $groups_team_count = count($groups_team);
                                if ($groups_team_count >= $groups['people_num'] || $groups['join_num'] >= $groups['people_num']) {
                                    $this->error(__('参与拼单失败，拼团已完成'));
                                }
                                // 判断是否具备成团条件
                                if (($groups['people_num'] - $groups_team_count) <= 1 || ($groups['people_num'] - $groups['join_num']) <= 1) {
                                    $groups_state = 'success';
                                    //调整其他拼团订单
                                    // 订单状态:1=待支付,2=待成团,3=待发货,4=待收货,5=待评论,6=已完成,7=已取消
                                    foreach ($groups_team as $team) {
                                        $order_list[] = ['id' => $team['order_id'], 'state' => 3, 'groupstime' => time()];
                                    }
                                }
                                // 拼团状态: ready=准备中,start=拼团中,success=已成团,fail=拼团失败,auto=自动成团
                                $groups_list[] = [
                                    'id' => $groups['id'],
                                    'join_num' => $groups['join_num'] + 1,
                                    'state' => $groups_state
                                ];
                                $groups_team_list[] = [
                                    'user_id' => $user_id, // 1.0.9升级
                                    'shop_id' => $goods['shop_id'],
                                    'group_no' => $goods['group_no'],
                                    'order_id' => $goods['order_id'],
                                    'order_goods_id' => $goods['id']
                                ];
                            }
                        }
                        // 新增付款人数、新增销量
                        $model_goods->where('id', $goods['goods_id'])->inc('payment')->inc('sales', $goods['number'])->update();
                    }
                    // 订单列表
                    if ($groups_state === 'success') {
                        $order_list[] = ['id' => $row['order_id'], 'state' => 3, 'paymenttime' => time(), 'groupstime' => time()];
                    } else {
                        $order_list[] = ['id' => $row['order_id'], 'state' => $isAlone ? 3 : 2, 'paymenttime' => time()];
                    }
                    // 支付列表 1.0.9升级
                    $pay_list[] = [
                        'id' => $row['id'],
                        'trade_no' => $trade_no, // 第三方交易号
                        'pay_type' => $pay_type, // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                        'pay_state' => 1, // 支付状态 (支付回调):0=未支付,1=已支付,2=已退款
                        'total_amount' => $price, // 总金额
                        'actual_payment' => $row['price'], // 实际支付
                        'notice' => json_encode($result)
                    ];
                }
                // 更新支付列表
                model('app\api\model\wanlshop\Pay')->saveAll($pay_list);
                // 更新订单列表
                $model_order->saveAll($order_list);
                //lina 新增 start
                $result = self::distribution($user_id, $pay[0]['order_id']);
                //lina 新增 end
            }
            //新增 判断会员等级购买 lina end
            // 支付日志
            model('app\common\model\MoneyLog')->create([
                'user_id' => $user_id,
                'money' => -$price, // 操作金额
                'memo' => $pay_name . '支付' . $order_type == 'groups' ? '拼团' : ($order_type == "userlevel" ? '会员卡' : '商城') . '订单', // 备注
                'type' => $order_type == 'groups' ? 'groups' : ($order_type == "userlevel" ? 'userlevel' : 'pay'), // 类型
                'service_ids' => implode(",", $order_no) // 业务ID
            ]);
            Log::debug('Wanlpay notify', $result->all());
            if ($order_type == 'groups') {
                model('app\api\model\wanlshop\groups\Groups')->isUpdate()->saveAll($groups_list);
                model('app\api\model\wanlshop\groups\Team')->saveAll($groups_team_list);
            }
            // 1.1.5升级 捕获异常
        } catch (\Exception $e) {
            return ['code' => 10008, 'msg' => $e->getMessage()];
        }
        // 返回给支付接口
        return ['code' => 200, 'msg' => $wanlpay->success()->send()];
    }

    /**
     * 充值支付回调
     */
    public function notify_recharge()
    {
        $wanlpay = Pay::{$this->type}(self::getConfig($this->type));
        try {
            $result = $wanlpay->verify();
            // 查询订单是否存在
            $order = model('app\api\model\wanlshop\RechargeOrder')
                ->where(['orderid' => $result['out_trade_no']])
                ->find();
            if (!$order) {
                return ['code' => 10001, 'msg' => '支付订单不存在'];
            } else {
                if ($order['status'] == 'paid') {
                    return ['code' => 10007, 'msg' => '订单已经支付过'];
                }
            }
            $memo = '';
            $trade_no = '';
            // -----------------------------判断订单是否合法-----------------------------
            $config = get_addon_config('wanlshop');
            // 支付宝
            if ($this->type == 'alipay') {
                // 判断状态
                if (in_array($result['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
                    // 判断金额
                    if ($order['amount'] != $result['total_amount']) {
                        return ['code' => 10002, 'msg' => '支付金额不合法'];
                    }
                    // 判断appid
                    if ($config['sdk_alipay']['app_id'] != $result['app_id']) {
                        return ['code' => 10003, 'msg' => 'APPID不合法'];
                    }
                } else {
                    return ['code' => 500, 'msg' => '支付回调失败'];
                }
                $memo = '支付宝充值';
                $trade_no = $result['trade_no'];
            } else if ($this->type == 'wechat') {
                // 判断状态
                if ($result['result_code'] == 'SUCCESS') {
                    // 判断金额
                    if ($order['amount'] != ($result['total_fee'] / 100)) {
                        return ['code' => 10002, 'msg' => '支付金额不合法'];
                    }
                    // 判断商家ID
                    if ($config['sdk_qq']['mch_id'] != $result['mch_id']) {
                        return ['code' => 10004, 'msg' => '商户不合法'];
                    }
                    // H5微信支付
                    if ($result['trade_type'] == 'MWEB') {
                        if ($config['sdk_qq']['gz_appid'] != $result['appid']) {
                            return ['code' => 10005, 'msg' => '支付类型 ' . $result['trade_type'] . ' 不合法'];
                        }
                    }
                    // 小程序支付
                    if ($result['trade_type'] == 'JSAPI') {
                        if ($config['mp_weixin']['appid'] != $result['appid']) {
                            if ($config['sdk_qq']['gz_appid'] != $result['appid']) {
                                return ['code' => 10006, 'msg' => '支付APPID不合法'];
                            }
                        }
                    }
                    // App支付
                    if ($result['trade_type'] == 'APP') {
                        if ($config['sdk_qq']['wx_appid'] != $result['appid']) {
                            return ['code' => 10007, 'msg' => '支付类型 ' . $result['trade_type'] . ' 不合法'];
                        }
                    }
                } else {
                    return ['code' => 500, 'msg' => '支付回调失败'];
                }
                $memo = '微信充值';
                $trade_no = $result['transaction_id'];
            }
            // -----------------------------支付成功，修改订单-----------------------------
            if ($order['status'] == 'created') {
                $order->memo = $trade_no;
                $order->payamount = $order['amount']; // 上面已经判断过金额，可以直接使用
                $order->paytime = time();
                $order->status = 'paid';
                $order->save();
                // 更新用户金额
                self::money(+$order['amount'], $order['user_id'], $memo, 'recharge', $order['id']);
            }
            Log::debug('Wanlpay notify', $result->all());
            // 1.1.5升级 捕获异常
        } catch (\Exception $e) {
            return ['code' => 10008, 'msg' => $e->getMessage()];
        }
        // 返回给支付接口
        return ['code' => 200, 'msg' => $wanlpay->success()->send()];
    }

    /**
     * 支付成功
     */
    public function return()
    {
        $wanlpay = Pay::{$this->type}(self::getConfig($this->type));
        try {
            return $wanlpay->verify();
            // 1.1.5升级 捕获异常
        } catch (\Exception $e) {
            return __($e->getMessage());
        }
    }

    /**
     * 退款回调
     */
    public function notify_refund()
    {
        $wanlpay = Pay::{$this->type}(self::getConfig($this->type));
        try {
            $result = $wanlpay->verify(null, true);
            // 支付宝
            if ($this->type == 'wechat') {
                $type_text = '微信支付';
                $money = bcdiv($result['refund_fee'], 100, 2);
                $pay_no = $result['out_refund_no'];
            } else if ($this->type == 'alipay') {
                $type_text = '支付宝支付';
                $money = $result['refund_amount'];
                $pay_no = $result['body'];
            }
            // 查询支付集
            // $payOutTrade = model('app\api\model\wanlshop\PayOutTrade')
            // 	->where('out_trade_no', 'eq', $result['out_trade_no'])
            // 	->find();
            // 查询订单是否存在
            $pay = model('app\api\model\wanlshop\Pay')
                ->where('pay_no', 'eq', $pay_no)
                ->where('pay_state', 'eq', '1')
                ->find();
            if ($pay) {
                $refund = model('app\api\model\wanlshop\Refund')
                    ->where([
                        'user_id' => $pay['user_id'],
                        'order_pay_id' => $pay['id'],
                        'order_id' => $pay['order_id'],
                        'order_type' => $pay['type']
                    ])
                    ->find();
                // 判断退款是否存在,退款状态是否第三方退款中状态
                if ($refund) {
                    if ($refund['state'] == '3' || $refund['state'] == '7') {
                        // 判断退款金额
                        if (bccomp($money, $refund['price'], 4) == 0) {
                            // 更新商品状态
                            $this->setOrderGoodsState(3, $refund['goods_ids'], $refund['order_type']);
                            // 更新订单状态
                            $this->setRefundState($refund['order_id'], $refund['order_type']);

                            // 写入日志
                            $this->refundLog($pay['user_id'], $refund['id'], $type_text . '退款处理成功，订单金额￥' . $refund['price'] . '元已到账');
                            // 推送开始
                            $this->pushRefund($refund['id'], $refund['order_id'], $refund['goods_ids'], '退款成功', $refund['order_type']);
                            // 更新退款
                            $refund->allowField(true)->save(['state' => 4, 'notice' => json_encode($result), 'completetime' => time()]);
                        } else {
                            // 写入日志
                            $this->refundLog($pay['user_id'], $refund['id'], $type_text . '退款订单异常，订单金额￥' . $refund['price'] . '元，实际退款金额￥' . $money . '元');
                            // 推送开始
                            $this->pushRefund($refund['id'], $refund['order_id'], $refund['goods_ids'], $type_text . '退款金额不匹配，退款失败', $refund['order_type']);
                            // 更新退款
                            $refund->allowField(true)->save(['state' => 8, 'notice' => json_encode($result), 'refuse_content' => $type_text . '退款失败，金额不匹配，请联系管理员']);
                        }
                    } else {
                        // 写入日志
                        $this->refundLog($pay['user_id'], $refund['id'], $type_text . '退款订单异常');
                        // 推送开始
                        $this->pushRefund($refund['id'], $refund['order_id'], $refund['goods_ids'], $type_text . '退款订单异常，退款失败', $refund['order_type']);
                        // 更新退款
                        $refund->allowField(true)->save(['state' => 8, 'notice' => json_encode($result), 'refuse_content' => $type_text . '退款订单不存在，请联系管理员']);
                    }
                }
            } else {
                return ['code' => 10001, 'msg' => '支付订单不存在'];
            }
        } catch (\Exception $e) {
            // 错误逻辑
            return ['code' => 10008, 'msg' => $e->getMessage()];
        }
        // 返回给支付接口
        return ['code' => 200, 'msg' => $wanlpay->success()->send()];
    }


    /**
     * 第三方退款
     * @param int $money 金额
     * @param int $pay_id 会员ID
     * @1.1.2升级 ~ 1.1.5升级
     */
    public function refund($refund_id, $money, $pay_id)
    {
        $type = '';
        $pay = model('app\api\model\wanlshop\Pay')->get($pay_id);
        if ($pay && $pay['pay_state'] == 1 && $pay['pay_type'] != 0) {
            // 1.1.3升级
            $trade = model('app\api\model\wanlshop\PayOutTrade')
                ->where([['EXP', Db::raw('FIND_IN_SET(' . $pay['id'] . ', pay_id)')]])
                ->find();
            if (!$trade) {
                return ['code' => 10009, 'msg' => '没有找到商户订单号'];
            }
            if ($pay['pay_type'] == 1) {
                $type = 'wechat';
                $type_text = '微信';
                // 退款订单
                $order['out_trade_no'] = $trade['out_trade_no'];
                $order['out_refund_no'] = $pay['pay_no']; //商家订单号
                // 分批退款
                if (count(explode(',', $trade['pay_id'])) > 1) {
                    // 总金额
                    $order['total_fee'] = bcmul(model('app\api\model\wanlshop\Pay')
                        ->where('id', 'in', $trade['pay_id'])
                        ->sum('price'), 100, 0);
                } else {
                    $order['total_fee'] = bcmul($pay['price'], 100, 0); // 订单金额
                }
                $order['refund_fee'] = bcmul($money, 100, 0);
                $order['refund_desc'] = '商城订单（订单号：' . $pay['order_no'] . '）退款' . $type_text . '账户￥' . $money . '元。';
                $notice = json_decode($pay['notice'], true);
                switch ($notice['trade_type']) {
                    case 'JSAPI':
                        $order['type'] = 'miniapp';
                        break;
                    case 'APP':
                        $order['type'] = 'app';
                        break;
                }
            } else if ($pay['pay_type'] == 2) {
                $type = 'alipay';
                $type_text = '支付宝';
                // 1.1.3升级
                $order['out_trade_no'] = $trade['out_trade_no'];
                $order['refund_amount'] = $money; //退款金额
                $order['refund_reason'] = '商城订单（订单号：' . $pay['order_no'] . '）退款买家' . $type_text . '账户￥' . $money . '元。'; //退款原因说明
                // 分批退款
                if (count(explode(',', $trade['pay_id'])) > 1) {
                    $order['out_request_no'] = $refund_id; //退款请求号
                }
            }
            // 退款 1.1.5升级
            try {
                $payConfig = self::getConfig($type);
                $payConfig['notify_url'] = str_replace("notify", "notify_refund", $payConfig['notify_url']);
                $wanlpay = Pay::{$type}($payConfig)->refund($order);
                $result = false;
                // 注意，接口中result_code=SUCCESS，仅代表本次退款请求成功，不代表退款成功
                if ($type == 'wechat' && $wanlpay->result_code == 'SUCCESS') {
                    // 关于微信退款:
                    // 微信退款不提供退款结果,仅返回退款请求成功,所以必须$result=true

                    // 通过回调来获取结果
                    $result = true;
                }
                // 注意，接口中code=10000，仅代表本次退款请求成功，不代表退款成功
                if ($type == 'alipay' && $wanlpay->code == '10000') {
                    // fund_change = Y，代表退款成功，支付宝文档《如何判断退款是否成功》，https://opendocs.alipay.com/support/01rawa
                    if ($wanlpay->fund_change == 'Y') {
                        return ['code' => 0, 'msg' => 'OK', 'data' => [
                            'money' => $money,
                            'user_id' => $pay['user_id'],
                            'type_text' => $type_text,
                            'refund_id' => $refund_id
                        ]];
                    } else {
                        // 通过回调来获取结果
                        // $result = true;

                        // 关于支付宝退款：
                        // 因测试订单时请求的均为 fund_change=Y 状态，即代表退款成功，可同步退款成功,以上注释支付宝文档《如何判断退款是否成功》
                        // 返回结果中的notify_url为配置的参数 也为notify_refund()方法,
                        // 但，实际服务器接收到异步回调为 notify()方法 且notify()中接受到的 TRADE_CLOSED交易状态为 "交易关闭"
                        // 目前等待支付宝进一步反馈，我们判断因为退款已成功fund_change=Y，所以返回notify() 为交易关闭
                        // 即使可以通过回调,可没有 同步fund_change=Y 状态安全可靠，已下

                        // 当前最佳最合理安全方案:
                        // 1.当 提交退款请求,且fund_change=Y同步完成退款(否则会出现已经给用户支付宝退款,但没有扣用户本地余额,会存在一定风险)
                        // 2.如果 极少数订单出现fund_change=N 时 code=10010中断第三方支付,使金额转到商城余额在手动提现，可避免任何风险产生
                        return ['code' => 10010, 'msg' => '提交退款未同步退款成功'];
                    }
                }
                if ($result) {
                    return ['code' => 200, 'msg' => 'OK', 'data' => [
                        'money' => $money,
                        'user_id' => $pay['user_id'],
                        'type_text' => $type_text,
                        'refund_id' => $refund_id
                    ]];
                } else {
                    return ['code' => 10009, 'msg' => '退款失败'];
                }
            } catch (\Exception $e) {
                return ['code' => 10008, 'msg' => $e->getMessage()];
            }
        } else {
            return ['code' => 1, 'msg' => '余额实时退款'];
        }
    }

    /**
     * 变更会员余额
     * @param int $money 余额
     * @param int $user_id 会员ID
     * @param string $memo 备注
     * @param string $type 类型
     * @param string $ids 业务ID
     */
    public static function money($money, $user_id, $memo, $type = '', $ids = '')
    {
        $user = model('app\common\model\User')->get($user_id);
        if ($user && $money != 0) {
            $before = $user->money;
            $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
            //更新会员信息
            $user->save(['money' => $after]);
            //写入日志
            $row = model('app\common\model\MoneyLog')->create([
                'user_id' => $user_id,
                'money' => $money, // 操作金额
                'before' => $before, // 原金额
                'after' => $after, // 增加后金额
                'memo' => $memo, // 备注
                'type' => $type, // 类型
                'service_ids' => $ids // 业务ID
            ]);
            return $row;
        } else {
            return ['code' => 500, 'msg' => '变更金额失败'];
        }
    }


    /**
     * 推送退款消息（方法内使用）
     *
     * @param string refund_id 订单ID
     * @param string order_id 订单ID
     * @param string goods_id 订单ID
     * @param string title 标题
     */
    private function pushRefund($refund_id = 0, $order_id = 0, $goods_id = 0, $title = '', $order_type = 'goods')
    {
        if ($order_type === 'groups') {
            $orderModel = model('app\index\model\wanlshop\groups\Order');
            $orderGoodsModel = model('app\index\model\wanlshop\groups\OrderGoods');
        } else {
            $orderModel = model('app\index\model\wanlshop\Order');
            $orderGoodsModel = model('app\index\model\wanlshop\OrderGoods');
        }
        $order = $orderModel->get($order_id);
        $goods = $orderGoodsModel->get($goods_id);
        $msg = [
            'user_id' => $order['user_id'], // 推送目标用户
            'shop_id' => $order['shop_id'],
            'title' => $title,  // 推送标题
            'image' => $goods['image'], // 推送图片
            'content' => '您申请退款的商品 ' . (mb_strlen($goods['title'], 'utf8') >= 25 ? mb_substr($goods['title'], 0, 25, 'utf-8') . '...' : $goods['title']) . ' ' . $title,
            'type' => 'order',  // 推送类型
            'modules' => $order_type === 'groups' ? 'groupsrefund' : 'refund',  // 模块类型
            'modules_id' => $refund_id,  // 模块ID
            'come' => '订单' . $order['order_no'] // 来自
        ];
        $this->wanlchat->send($order['user_id'], $msg);
        $notice = model('app\index\model\wanlshop\Notice');
        $notice->data($msg);
        $notice->allowField(true)->save();
    }

    /**
     * 更新订单商品状态（方法内使用）
     *
     * @ApiSummary  (WanlShop 更新订单商品状态)
     * @ApiMethod   (POST)
     *
     * @param string $status 状态
     * @param string $goods_id 商品ID
     */
    private function setOrderGoodsState($status = 0, $goods_id = 0, $order_type = 'goods')
    {
        if ($order_type === 'groups') {
            $orderGoodsModel = model('app\index\model\wanlshop\groups\OrderGoods');
        } else {
            $orderGoodsModel = model('app\index\model\wanlshop\OrderGoods');
        }
        return $orderGoodsModel->save(['refund_status' => $status], ['id' => $goods_id]);
    }


    /**
     * 修改订单状态（方法内使用） 1.0.5升级
     *
     * @ApiSummary  (WanlShop 修改订单状态)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    private function setRefundState($order_id = 0, $order_type = 'goods')
    {
        if ($order_type === 'groups') {
            $orderModel = model('app\index\model\wanlshop\groups\Order');
            $orderGoodsModel = model('app\index\model\wanlshop\groups\OrderGoods');
        } else {
            $orderModel = model('app\index\model\wanlshop\Order');
            $orderGoodsModel = model('app\index\model\wanlshop\OrderGoods');
        }
        $list = $orderGoodsModel
            ->where(['order_id' => $order_id])
            ->select();
        $refundStatusCount = 0;
        foreach ($list as $row) {
            if ($row['refund_status'] == 3) $refundStatusCount += 1;
        }
        // 如果订单下所有商品全部退款完毕则关闭订单
        if (count($list) == $refundStatusCount) {
            $orderModel->save(['state' => 7], ['id' => $order_id]);
            return true;
        }
        return false;
    }

    /**
     * 退款日志（方法内使用）
     *
     * @ApiSummary  (WanlShop 退款日志)
     * @ApiMethod   (POST)
     *
     * @param string $user_id 用户ID
     * @param string $refund_id 退款ID
     * @param string $content 日志内容
     * @param string $type 退款状态:0=买家,1=卖家,2=官方,3=系统
     */
    private function refundLog($user_id = 0, $refund_id = 0, $content = '', $type = 3)
    {
        return model('app\index\model\wanlshop\RefundLog')->allowField(true)->save([
            'user_id' => $user_id,
            'refund_id' => $refund_id,
            'type' => $type,
            'content' => $content
        ]);
    }


    /**
     * 获取配置 1.1.2升级
     * @param string $type 支付类型
     * @return array|mixed
     */
    private function getConfig($type)
    {
        $config = get_addon_config('wanlshop');
        $pay_config = [];
        if ($type == 'alipay') {
            $pay_config = [
                'app_id' => $config['sdk_alipay']['app_id'],
                'notify_url' => $config['ini']['appurl'] . $config['sdk_alipay']['notify_url'],
                'return_url' => $config['ini']['appurl'] . $config['sdk_alipay']['return_url'],
                'private_key' => $config['sdk_alipay']['private_key'],
                'log' => [
                    'file' => LOG_PATH . 'wanlpay' . DS . $type . '-' . date("Y-m-d") . '.log',
                    'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                    'type' => 'single', // optional, 可选 daily.
                    'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
                ],
                'http' => [
                    'timeout' => 5.0,
                    'connect_timeout' => 5.0
                ],
            ];
            if (isset($config['sdk_alipay']['app_cert_public_key']) && substr($config['sdk_alipay']['app_cert_public_key'], 0, 8) == '/addons/') {
                $pay_config['app_cert_public_key'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_alipay']['app_cert_public_key'], 1));
            }
            if (isset($config['sdk_alipay']['alipay_root_cert']) && substr($config['sdk_alipay']['alipay_root_cert'], 0, 8) == '/addons/') {
                $pay_config['alipay_root_cert'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_alipay']['alipay_root_cert'], 1));
            }
            if (isset($config['sdk_alipay']['ali_public_key']) && (Str::endsWith($config['sdk_alipay']['ali_public_key'], '.crt') || Str::endsWith($config['sdk_alipay']['ali_public_key'], '.pem'))) {
                $pay_config['ali_public_key'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_alipay']['ali_public_key'], 1));
            }
        } else if ($type == 'wechat') {
            $pay_config = [
                'appid' => $config['sdk_qq']['wx_appid'], // APP APPID
                'app_id' => $config['sdk_qq']['gz_appid'], // 公众号 APPID
                'miniapp_id' => $config['mp_weixin']['appid'], // 小程序 APPID
                'mch_id' => $config['sdk_qq']['mch_id'],
                'key' => $config['sdk_qq']['key'],
                'notify_url' => $config['ini']['appurl'] . $config['sdk_qq']['notify_url'],
                // 1.0.8升级 回调 https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_4
                'return_url' => $config['h5']['domain'] . ($config['h5']['router_mode'] == 'hash' ? '/#' : '') . '/pages/page/success?type=pay',
                'log' => [
                    'file' => LOG_PATH . 'wanlpay' . DS . $type . '-' . date("Y-m-d") . '.log',
                    'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                    'type' => 'single', // optional, 可选 daily.
                    'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
                ],
                'http' => [
                    'timeout' => 5.0,
                    'connect_timeout' => 5.0,
                    // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
                ],
            ];
            if (isset($config['sdk_qq']['cert_client']) && substr($config['sdk_qq']['cert_client'], 0, 8) == '/addons/') {
                $pay_config['cert_client'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_qq']['cert_client'], 1));
            }
            if (isset($config['sdk_qq']['cert_key']) && substr($config['sdk_qq']['cert_key'], 0, 8) == '/addons/') {
                $pay_config['cert_key'] = ROOT_PATH . str_replace('/', DS, substr($config['sdk_qq']['cert_key'], 1));
            }
        }
        return $pay_config;
    }

    //新增 修改用户等级

    /**
     * 修改用户等级
     * @param int $money 余额
     * @param int $user_id 会员ID
     * @param string $memo 备注
     * @param string $type 类型
     * @param string $ids 业务ID
     */
    /*public static function updateUserLevel($user_id, $order_id)
    {
        $user = model('app\common\model\User')->get($user_id);
        $Usermodel = new \app\common\model\User();
        $model = new LevelOrder();
        $order = $model->get($order_id);
        if ($user && !empty($order)) {
            //计算现金补贴最后一天 start
            $config = get_addon_config('wanlshop');
            $radio_use_day = $config["subsidy"]["radio_use_day"] ?? 10;//有效期天数
            $end_day = ceil($order["subsidy_money"] / $order["daily_money"]);
            $date = strtotime('+' . ($radio_use_day + $end_day + 1) . ' day', time());
            $order->save(["state" => '2', "paymenttime" => time(), "end_granttime" => $date]);
            //计算现金补贴最后一天 end
            $goods = model('app\api\model\wanlshop\Goods')
                ->where(['id' => $order["goods_id"], 'status' => 'normal'])
                ->find();
            if (!empty($goods)) {
                // 获取店铺ID
                $shop_id = $goods['shop_id'];
                // 生成订单
                $shopOrder = new \app\api\model\wanlshop\Order;
                $order_goods=$shopOrder->where(["level_order_id"=>$order["id"],"type"=>1])->find();
                if(empty($order_goods)){
                    $shopOrder->freight_type = 0;
                    $shopOrder->user_id = $user_id;
                    $shopOrder->shop_id = $shop_id;
                    $shopOrder->order_no = $order->order_no;
                    $shopOrder->level_order_id = $order->id;
                    $shopOrder->coupon_id = 0;
                    $shopOrder->type = 1;
                    $shopOrder->state = 2;
                    $shopOrder->paymenttime = time();
                    $sku = model('app\api\model\wanlshop\GoodsSku')->where(["goods_id" => $goods['id']])->find();
                    // 商品列表 actual_payment
                    $shopOrder->save();
                    $shopGoodsAll = [
                        'order_id' => $shopOrder->id, // 获取自增ID
                        'goods_id' => $goods['id'],
                        'shop_id' => $shop_id,
                        'title' => $goods['title'],
                        'image' => $goods['image'],
                        'goods_sku_sn' => $sku['sn'],
                        'goods_sku_id' => $sku['id'],
                        'difference' => join(',', $sku['difference']),
                        'market_price' => $sku['market_price'], // 市场价
                        'price' => $sku['price'], // 原价
                        'freight_price' => 0, //快递价格
                        'discount_price' => 0, // 优惠金额
                        'actual_payment' => 0, // 1.0.6修复 实际支付，因为要和总价进行计算
                        'number' => 1
                    ];
                    $address = json_decode($user["permanent"], true);
                    // 生成地址
                    $addressList = [
                        'user_id' => $user_id,
                        'shop_id' => $shop_id,
                        'order_id' => $shopOrder->id,
                        'name' => $address['name']??'',
                        'mobile' => $address['mobile']??'',
                        'address' => $address['province'] . '/' . $address['city'] . '/' . $address['district'] . '/' . $address['address']??'',
                        'address_name' => $address['address_name']??'',
                        'location' => $address['location']??'',
                    ];
                    model('app\api\model\wanlshop\OrderAddress')->save($addressList);
                    model('app\api\model\wanlshop\OrderGoods')->save($shopGoodsAll);
                }
            }
            $distribution = model('app\common\model\Distribution')->where(["order_no" => $order["order_no"], "type" => 1])->find();
            if (!empty($user["agent_id"])) {
                //通过上级分享购买等级
                $agent = model('app\common\model\User')->get($user["agent_id"]);
            } else {
                $agent = model('app\common\model\User')->get($order["agent_id"]);
            }
            if ($user["identity"] == 1) {
                //如果是团队长自购
                $agent = $user;
            }
            // identity 身份:0=分销商 1团长 2区域代理 3员工
            if (empty($distribution)) {
                if (!empty($agent)) {
                    $agent_bind=$agent;
                    $agent_status=false;
                    if(!empty($agent["agent_id"])){
                        $agent_parter=model('app\common\model\User')->get($agent["agent_id"]);//查找我上上级是什么身份
                        if (!empty($agent_parter)){
                            if ($agent_parter["is_staff"] == 1 && !empty($agent_parter["team_id"])){
                                //上上级是员工
                                $agent_status=3;
                                $agent_parter=model('app\common\model\User')->get($agent_parter["team_id"]);//查找我上上级是什么身份
                            }
                            if($agent_parter["identity"]==1){
                                //上上级是团长
                                $agent_status=1;
                            }
                        }
                    }
                    if (($agent["identity"] == 1 || $agent["is_staff"] == 1) || $agent_status) {
                        //我的上级是团长或者是员工
                        //钱分给团长
                        if($agent_status && !($agent["identity"] == 1 || $agent["is_staff"] == 1)){
                            $agent=$agent_parter;
                        }
                        if ($agent["team_status"] == 1) {
                            $remark = '';
                            $commiss_user_id = $agent["id"];
                            if ($agent["is_staff"] == 1) {
                                $commiss_user_id = $agent["team_id"];
                            }
                            $identity = 1;
                            $team_level_id = \app\common\model\team\Level::alias("level")
                                ->field("level.rebate")
                                ->join("user user", "level.id=user.team_level_id")
                                ->where(["user.id" => $agent["team_id"]])->find();
                            if (!empty($team_level_id)) {
                                $rebate = $team_level_id["rebate"] / 100;
                            } else {
                                $rebate = 0.5;
                            }
                            $money = bcmul($order["money"], $rebate, 2);
                            $rebate_content = [
                                "level_id" => $agent["team_level_id"] ?? 0,
                                "rebate" => $rebate,
                                "money" => $money,
                                "level_money" => $order["money"],
                            ];
                            $rebate_content = json_encode($rebate_content);
                            $distributionList[] = [
                                'type' => 1,//1会员等级订单 2商品订单
                                'order_no' => $order["order_no"],
                                'money' => $money,//佣金
                                'agent_id' => $agent["id"],
                                'commiss_user_id' => $commiss_user_id,//分钱用户id
                                'identity' => 1,//分钱人身份 0分销商 1团长 2区域合伙人 4员工
                                'user_id' => $order["user_id"],
                                'level_id' => $order["level_id"],
                                'remark' => $remark,
                                'status' => 1,
                                'rebate_content' => $rebate_content,
                                'order_id' => $order["id"],
                            ];
                            $Usermodel->commission($money,$commiss_user_id,"团员购买会员卡分佣",$order["id"],$order["order_no"],$identity);
                        }
                    }else{
                        //上级和不是团长也不是员工  --上上级不是员工
                        $identity = $agent["identity"];
                        $money = 0;
                        $remark = "";//,2
                        if (empty($agent["is_staff"]) && !in_array($identity, [1, 3]) && $agent["level_id"] > 0) {
                            //推荐人不是员工
                            $commiss_user_id = $agent["id"];
                            if ($identity == 2) {
                                //区域合伙人
                                $identity = 0;
                            }
                            $count = model('app\common\model\Distribution')->where(["commiss_user_id" => $agent["id"], "identity" => $identity, "type" => 1])->count();
                            $remark = "推三返一订单，加油~";
                            if ($count == 2) {
                                $remark = "推三返一";
                                $level = Level::find($agent["level_id"]);
                                $money = $level["price"];
                                if ($agent["level_id"] > 0) {
                                    if ($order["level_id"] == 1) {
                                        $money = $order["money"];
                                    } else {
                                        //查找前两个是否金额都和上级等级金额一致
                                        $list = model('app\common\model\Distribution')->field("GROUP_CONCAT(DISTINCT level_id) level_id")
                                            ->where(["commiss_user_id" => $agent["id"], "identity" => $identity, "type" => 1])
                                            ->order("createtime", "desc")->limit(0, 2)->select();
                                        $level_id = explode(",", $list[0]["level_id"]);
                                        if (!in_array(1, $level_id)) {
                                            $money = $order["money"];
                                        } else {
                                            $level = Level::find(1);
                                            $money = $level["price"];
                                        }
                                    }
                                }
                                //新增---完成三返一再次发放现金补贴 start
                                if ($config["subsidy"]["finish_grant"] == "Y") {
                                    //开启完成三返一再次发放现金补贴
                                    $day_radio = $config["subsidy"]["day_radio"] ?? 10;//每日到账比例
                                    $level["day_radio"] = $day_radio;
                                    $daily_money = bcmul($level["subsidy"], ($day_radio / 100), 2);
                                    $end_day = ceil($level["subsidy"] / $daily_money);
                                    $date = strtotime('+' . ($radio_use_day + $end_day + 1) . ' day', time());
                                    $grant_id = PerkGrant::insertGetId([
                                        "user_ids" => $agent["id"],
                                        "remarks" => "完成三返一再次发送现金补贴",
                                        "subsidy_money" => $level["subsidy"],
                                        "residue_money" => $level["subsidy"],
                                        "daily_money" => $daily_money,//每日到账x元
                                        "end_granttime" => $date,
                                        "createtime" => time(),
                                        "day" => $end_day,
                                        "type_data" => 2,
                                    ]);
                                    $order_data = [
                                        "user_id" => $agent["id"],
                                        "state" => 2,
                                        "level_id" => 0,
                                        "order_no" => "sfy".md5(time()),
                                        "level_details" => json_decode($level),
                                        "subsidy_money" => $level["subsidy"],
                                        "residue_money" => $level["subsidy"],
                                        "daily_money" => $daily_money,//每日到账x元
                                        "end_granttime" => $date,
                                        "goods_id" => 0,
                                        "agent_id" => 0,
                                        "createtime" => time(),
                                        "type" => 2,
                                        "grant_id" => $grant_id,
                                    ];
                                    $orderModel = new LevelOrder();
                                    $orderModel->save($order_data);
                                }
                                //新增---完成三返一再次发放现金补贴 end
                            }
                            if ($count >= 3) {
                                $money = bcmul($order["money"], 0.2, 2);
                                $remark = "返利20%";
                            }
                            $rebate_content = [
                                "level_id" => $agent["team_level_id"] ?? 0,
                                "rebate" => "",
                                "money" => $money,
                                "level_money" => $order["money"],
                            ];
                            $rebate_content = json_encode($rebate_content);
                            $distributionList[] = [
                                'type' => 1,//1会员等级订单 2商品订单
                                'order_no' => $order["order_no"],
                                'money' => $money,//佣金
                                'agent_id' => $agent["id"],
                                'commiss_user_id' => $commiss_user_id,//分钱用户id
                                'identity' => $identity,//分钱人身份 0分销商 1团长 2区域合伙人
                                'user_id' => $order["user_id"],
                                'level_id' => $order["level_id"],
                                'remark' => $remark,
                                'status' => 1,
                                'rebate_content' => $rebate_content,
                                'order_id' => $order["id"],
                            ];
                            //2023-11-9 lina start

                            $Usermodel->commission($money, $commiss_user_id, "下级购买会员卡分佣", $order["id"], $order["order_no"]);
                            //2023-11-9 lina end
                        }
                    }
                }
                if ((!empty($agent) && ($agent["is_staff"] != 1 && $agent["identity"] != 1)) || empty($agent)) {
                    //查找区域合伙人--给区域合伙人分钱
                    $permanent = json_decode($user["permanent"], true);
                    $region = User::where(["identity" => 2, "region_status" => 1])
                        ->where('FIND_IN_SET("' . $permanent["province_id"] . '", region_address) or FIND_IN_SET("' . $permanent["city_id"] . '", region_address)  or FIND_IN_SET("' . $permanent["district_id"] . '", region_address)')
                        ->find();
                    if (!empty($region)) {
                        $region_level = RegionLevel::where(["id" => $region["region_level_id"]])->find();
                        if (!empty($region_level) && !empty($region_level["rebate"])) {
                            $rebate = $region_level["rebate"] / 100;
                        } else {
                            $rebate = 0.15;
                        }
                        $money = bcmul($order["money"], $rebate, 2);
                        $rebate_content = [
                            "level_id" => $region["region_level_id"] ?? 0,
                            "rebate" => $rebate,
                            "money" => $money,
                            "level_money" => $order["money"],
                        ];
                        $rebate_content = json_encode($rebate_content);
                        $distributionList[] = [
                            'type' => 1,//1会员等级订单 2商品订单
                            'order_no' => $order["order_no"],
                            'money' => $money,//佣金
                            'agent_id' => $agent["id"] ?? 0,
                            'commiss_user_id' => $region["id"],//分钱用户id
                            'identity' => 2,//分钱人身份 0分销商 1团长 2区域合伙人 4员工
                            'user_id' => $order["user_id"],
                            'level_id' => $order["level_id"],
                            'remark' => "区域下用户购买会员卡分佣",
                            'status' => 1,
                            'rebate_content' => $rebate_content,
                            'order_id' => $order["id"],
                        ];
                        //区域代理--给区域代理钱包加钱
                        $Usermodel->region_commission($money, $region["id"], "下级购买会员卡分佣", $order["id"], $order["order_no"], 0);
                        //$result = self::money($money, $region["id"], '区域下用户购买会员卡分佣','userlevel', $order["order_no"]);
                        //$Usermodel->commission($money,$region["id"],"区域下用户购买会员卡分佣",$order["id"],$order["order_no"],2);
                    }
                }
                if (!empty($distributionList)) {
                    model('app\common\model\Distribution')->saveAll($distributionList);//分销订单数据记录
                }
                if (empty($user["agent_id"]) && empty($user["level_id"]) && !empty($agent_bind)) {
                    if (!empty($agent_bind["team_id"])) {
                        $user->team_id = $agent_bind["team_id"];//团长
                    }
                    if ($agent_bind["identity"] == 1) {
                        $user->team_id = $agent_bind["id"];//团长
                    }
                    $user->agent_id = $agent_bind["id"];
                    $user->save();
                }
            }
            $user->save(['level_id' => $order["level_id"]]);
            return true;
        } else {
            return ['code' => 500, 'msg' => '变更用户等级失败'];
        }
    }*/
    //2023-12-20
    //团长和员工不参与三返一
    public static function updateUserLevel($user_id, $order_id)
    {
        $user = model('app\common\model\User')->get($user_id);
        $Usermodel = new \app\common\model\User();
        $model = new LevelOrder();
        $order = $model->get($order_id);
        //如果上级推荐
        $agent_level=true;
        $agent_bind_status=true;
        if(!empty($order["agent_id"])){
            $user_agent = model('app\common\model\User')->field("id,agent_id,level_id,is_staff,identity,team_status,region_status")->where(["id"=>$order["agent_id"]])->find();
            if($user_agent){
                if($user_agent["level_id"]<=1 && (empty($user_agent["is_staff"]) || $user_agent["identity"]!=3)) $agent_level=false;
                //暂时先注释员工、团长、区域合伙人禁用不绑定推荐关系
                if(($user["is_staff"]==1 || $user_agent["identity"]==3) && empty($user_agent["staff_status"])){
                    //员工禁用
                    $agent_bind_status=false;
                }
                if($user_agent["identity"]==1 && empty($user_agent["team_status"])){
                    //团长禁用
                    $agent_bind_status=false;
                }
                if($user_agent["identity"]==2 && empty($user_agent["region_status"])){
                    //区域合伙人禁用
                    $agent_bind_status=false;
                }
                //如果上级是员工查询员工上级的团长是否被禁用
                if($agent_bind_status==true && (empty($user_agent["is_staff"]) || $user_agent["identity"]!=3)){
                    $user_agent_parent = model('app\common\model\User')->field("agent_id,level_id,is_staff,identity,team_status,region_status")->where(["id"=>$user_agent["id"]])->find();
                    if($user_agent_parent["identity"]==1 && empty($user_agent_parent["team_status"])){
                        $agent_bind_status=false;
                    }
                }
            }
        }
        if ($user && !empty($order)) {
            //计算现金补贴最后一天 start
            $config = get_addon_config('wanlshop');
            $radio_use_day = $config["subsidy"]["radio_use_day"] ?? 10;//有效期天数
            $end_day = ceil($order["subsidy_money"] / $order["daily_money"]);
            $date = strtotime('+' . ($radio_use_day + $end_day + 1) . ' day', time());
            $order->save(["state" => '2', "paymenttime" => time(), "end_granttime" => $date]);
            //计算现金补贴最后一天 end
            $goods = model('app\api\model\wanlshop\Goods')
                ->where(['id' => $order["goods_id"], 'status' => 'normal'])
                ->find();
            if (!empty($goods)) {
                // 获取店铺ID
                $shop_id = $goods['shop_id'];
                // 生成订单
                $shopOrder = new \app\api\model\wanlshop\Order;
                $order_goods = $shopOrder->where(["level_order_id" => $order["id"], "type" => 1])->find();
                if (empty($order_goods)) {
                    $shopOrder->freight_type = 0;
                    $shopOrder->user_id = $user_id;
                    $shopOrder->shop_id = $shop_id;
                    $shopOrder->order_no = $order->order_no;
                    $shopOrder->level_order_id = $order->id;
                    $shopOrder->coupon_id = 0;
                    $shopOrder->type = 1;
                    $shopOrder->state = 2;
                    $shopOrder->paymenttime = time();
                    $sku = model('app\api\model\wanlshop\GoodsSku')->where(["goods_id" => $goods['id'],"state"=>0])->find();
                    // 商品列表 actual_payment
                    $shopOrder->save();
                    $shopGoodsAll = [
                        'order_id' => $shopOrder->id, // 获取自增ID
                        'goods_id' => $goods['id'],
                        'shop_id' => $shop_id,
                        'title' => $goods['title'],
                        'image' => $goods['image'],
                        'goods_sku_sn' => $sku['sn'],
                        'goods_sku_id' => $sku['id'],
                        'difference' => join(',', $sku['difference']),
                        'market_price' => $sku['market_price'], // 市场价
                        'price' => $sku['price'], // 原价
                        'freight_price' => 0, //快递价格
                        'discount_price' => 0, // 优惠金额
                        'actual_payment' => 0, // 1.0.6修复 实际支付，因为要和总价进行计算
                        'number' => 1
                    ];
                    $address = json_decode($user["permanent"], true);
                    // 生成地址
                    $addressList = [
                        'user_id' => $user_id,
                        'shop_id' => $shop_id,
                        'order_id' => $shopOrder->id,
                        'name' => $address['name'] ?? '',
                        'mobile' => $address['mobile'] ?? '',
                        'address' => $address['province'] . '/' . $address['city'] . '/' . $address['district'] . '/' . $address['address'] ?? '',
                        'address_name' => $address['address_name'] ?? '',
                        'location' => $address['location'] ?? '',
                    ];
                    model('app\api\model\wanlshop\OrderAddress')->save($addressList);
                    model('app\api\model\wanlshop\OrderGoods')->save($shopGoodsAll);
                }
            }
            $distribution = model('app\common\model\Distribution')->where(["order_no" => $order["order_no"], "type" => 1])->find();
            if($agent_level){
                if (!empty($user["agent_id"])) {
                    //通过上级分享购买等级
                    $agent = model('app\common\model\User')->get($user["agent_id"]);
                } else {
                    $agent = model('app\common\model\User')->get($order["agent_id"]);
                }
                if ($user["identity"] == 1) {
                    //如果是团队长自购
                    $agent = $user;
                }
                // identity 身份:0=分销商 1团长 2区域代理 3员工
                if (empty($distribution)) {
                    if (!empty($agent)) {
                        $agent_bind = $agent;
                        if ($agent_bind_status && ($agent["identity"] == 1 || $agent["is_staff"] == 1)) {
                            //我的上级是团长或者是员工
                            //钱分给团长
                            if ($agent["team_status"] == 1) {
                                $remark = '';
                                $commiss_user_id = $agent["id"];
                                if ($agent["is_staff"] == 1) {
                                    $commiss_user_id = $agent["team_id"];
                                }
                                $identity = 1;
                                $team_level_id = \app\common\model\team\Level::alias("level")
                                    ->field("level.rebate")
                                    ->join("user user", "level.id=user.team_level_id")
                                    ->where(["user.id" => $agent["team_id"]])->find();
                                if (!empty($team_level_id)) {
                                    $rebate = $team_level_id["rebate"] / 100;
                                } else {
                                    $rebate = 0.5;
                                }
                                $money = bcmul($order["money"], $rebate, 2);
                                $rebate_content = [
                                    "level_id" => $agent["team_level_id"] ?? 0,
                                    "rebate" => $rebate,
                                    "money" => $money,
                                    "level_money" => $order["money"],
                                ];
                                $rebate_content = json_encode($rebate_content);
                                $distributionList[] = [
                                    'type' => 1,//1会员等级订单 2商品订单
                                    'order_no' => $order["order_no"],
                                    'money' => $money,//佣金
                                    'agent_id' => $agent["id"],
                                    'commiss_user_id' => $commiss_user_id,//分钱用户id
                                    'identity' => 1,//分钱人身份 0分销商 1团长 2区域合伙人 4员工
                                    'user_id' => $order["user_id"],
                                    'level_id' => $order["level_id"],
                                    'remark' => $remark,
                                    'status' => 1,
                                    'rebate_content' => $rebate_content,
                                    'order_id' => $order["id"],
                                ];
                                $Usermodel->commission($money, $commiss_user_id, "团员购买会员卡分佣", $order["id"], $order["order_no"], $identity);
                            }
                        } else {
                            //上级和不是团长也不是员工  --上上级不是员工
                            $identity = $agent["identity"];
                            $money = 0;
                            if (empty($agent["is_staff"]) && !in_array($identity, [1, 3]) && $agent["level_id"] > 0) {
                                //推荐人不是员工
                                $commiss_user_id = $agent["id"];
                                if ($identity == 2) {
                                    //区域合伙人
                                    $identity = 0;
                                }
                                $count = model('app\common\model\Distribution')->where(["commiss_user_id" => $agent["id"], "identity" => $identity, "type" => 1])->count();
                                $remark = "推三返一订单，加油~";
                                if ($count == 2) {
                                    $remark = "推三返一";
                                    $level = Level::find($agent["level_id"]);
                                    $money = $level["price"];
                                    if ($agent["level_id"] > 0) {
                                        if ($order["level_id"] == 1) {
                                            $money = $order["money"];
                                        } else {
                                            //查找前两个是否金额都和上级等级金额一致
                                            $list = model('app\common\model\Distribution')->field("GROUP_CONCAT(DISTINCT level_id) level_id")
                                                ->where(["commiss_user_id" => $agent["id"], "identity" => $identity, "type" => 1])
                                                ->order("createtime", "desc")->limit(0, 2)->select();
                                            $level_id = explode(",", $list[0]["level_id"]);
                                            if (!in_array(1, $level_id)) {
                                                $money = $order["money"];
                                            } else {
                                                $level = Level::find(1);
                                                $money = $level["price"];
                                            }
                                        }
                                    }
                                    //新增---完成三返一再次发放现金补贴 start
                                    if ($config["subsidy"]["finish_grant"] == "Y") {
                                        //开启完成三返一再次发放现金补贴
                                        $day_radio = $config["subsidy"]["day_radio"] ?? 10;//每日到账比例
                                        $level["day_radio"] = $day_radio;
                                        $daily_money = bcmul($level["subsidy"], ($day_radio / 100), 2);
                                        $end_day = ceil($level["subsidy"] / $daily_money);
                                        $date = strtotime('+' . ($radio_use_day + $end_day + 1) . ' day', time());
                                        $grant_id = PerkGrant::insertGetId([
                                            "user_ids" => $agent["id"],
                                            "remarks" => "完成三返一再次发送现金补贴",
                                            "subsidy_money" => $level["subsidy"],
                                            "residue_money" => $level["subsidy"],
                                            "daily_money" => $daily_money,//每日到账x元
                                            "end_granttime" => $date,
                                            "createtime" => time(),
                                            "day" => $end_day,
                                            "type_data" => 2,
                                        ]);
                                        $order_data = [
                                            "user_id" => $agent["id"],
                                            "state" => 2,
                                            "level_id" => 0,
                                            "order_no" => "sfy" . md5(time()),
                                            "level_details" => json_decode($level),
                                            "subsidy_money" => $level["subsidy"],
                                            "residue_money" => $level["subsidy"],
                                            "daily_money" => $daily_money,//每日到账x元
                                            "end_granttime" => $date,
                                            "goods_id" => 0,
                                            "agent_id" => 0,
                                            "createtime" => time(),
                                            "type" => 2,
                                            "grant_id" => $grant_id,
                                        ];
                                        $orderModel = new LevelOrder();
                                        $orderModel->save($order_data);
                                    }
                                    //新增---完成三返一再次发放现金补贴 end
                                }
                                if ($count >= 3) {
                                    $money = bcmul($order["money"], 0.2, 2);
                                    $remark = "返利20%";
                                }
                                $rebate_content = [
                                    "level_id" => $agent["team_level_id"] ?? 0,
                                    "rebate" => "",
                                    "money" => $money,
                                    "level_money" => $order["money"],
                                ];
                                $rebate_content = json_encode($rebate_content);
                                $distributionList[] = [
                                    'type' => 1,//1会员等级订单 2商品订单
                                    'order_no' => $order["order_no"],
                                    'money' => $money,//佣金
                                    'agent_id' => $agent["id"],
                                    'commiss_user_id' => $commiss_user_id,//分钱用户id
                                    'identity' => $identity,//分钱人身份 0分销商 1团长 2区域合伙人
                                    'user_id' => $order["user_id"],
                                    'level_id' => $order["level_id"],
                                    'remark' => $remark,
                                    'status' => 1,
                                    'rebate_content' => $rebate_content,
                                    'order_id' => $order["id"],
                                ];
                                $Usermodel->commission($money, $commiss_user_id, "下级购买会员卡分佣", $order["id"], $order["order_no"]);
                            }
                        }
                    }
                    if ($agent_bind_status && ((!empty($agent) && ($agent["is_staff"] != 1 && $agent["identity"] != 1)) || empty($agent))) {
                        //查找区域合伙人--给区域合伙人分钱
                        $permanent = json_decode($user["permanent"], true);
                        $region = User::where(["identity" => 2, "region_status" => 1])
                            ->where('FIND_IN_SET("' . $permanent["province_id"] . '", region_address) or FIND_IN_SET("' . $permanent["city_id"] . '", region_address)  or FIND_IN_SET("' . $permanent["district_id"] . '", region_address)')
                            ->find();
                        if (!empty($region)) {
                            $region_level = RegionLevel::where(["id" => $region["region_level_id"]])->find();
                            if (!empty($region_level) && !empty($region_level["rebate"])) {
                                $rebate = $region_level["rebate"] / 100;
                            } else {
                                $rebate = 0.15;
                            }
                            $money = bcmul($order["money"], $rebate, 2);
                            $rebate_content = [
                                "level_id" => $region["region_level_id"] ?? 0,
                                "rebate" => $rebate,
                                "money" => $money,
                                "level_money" => $order["money"],
                            ];
                            $rebate_content = json_encode($rebate_content);
                            $distributionList[] = [
                                'type' => 1,//1会员等级订单 2商品订单
                                'order_no' => $order["order_no"],
                                'money' => $money,//佣金
                                'agent_id' => $agent["id"] ?? 0,
                                'commiss_user_id' => $region["id"],//分钱用户id
                                'identity' => 2,//分钱人身份 0分销商 1团长 2区域合伙人 4员工
                                'user_id' => $order["user_id"],
                                'level_id' => $order["level_id"],
                                'remark' => "区域下用户购买会员卡分佣",
                                'status' => 1,
                                'rebate_content' => $rebate_content,
                                'order_id' => $order["id"],
                            ];
                            //区域代理--给区域代理钱包加钱
                            $Usermodel->region_commission($money, $region["id"], "下级购买会员卡分佣", $order["id"], $order["order_no"], 0);
                        }
                    }
                    if (!empty($distributionList)) {
                        model('app\common\model\Distribution')->saveAll($distributionList);//分销订单数据记录
                    }
                    if (empty($user["agent_id"]) && (empty($user["level_id"]) || $user["level_id"]==1) && !empty($agent_bind)) {
                        if (!empty($agent_bind["team_id"])) {
                            $user->team_id = $agent_bind["team_id"];//团长
                        }
                        if ($agent_bind["identity"] == 1) {
                            $user->team_id = $agent_bind["id"];//团长
                        }
                        $user->agent_id = $agent_bind["id"];
                        $user->save();
                    }
                }
            }
            $user->save(['level_id' => $order["level_id"]]);
            return true;
        } else {
            return ['code' => 500, 'msg' => '变更用户等级失败'];
        }
    }

    /**
     * 用户购买给团长或区域合伙人分佣
     * */
    public static function distribution($user_id, $order_id)
    {
        $user = model('app\common\model\User')->get($user_id);
        //$Usermodel=new \app\common\model\User();
        $model = new Order();
        $order = $model->get($order_id);
        $model_order_goods = model('app\api\model\wanlshop\OrderGoods');
        $order_goods = $model_order_goods->whereIn('order_id', $order_id)->select();
        file_put_contents("abc.txt",json_encode($order_goods).PHP_EOL,FILE_APPEND);
        if ($user && !empty($order) && !empty($order_goods)) {
            foreach ($order_goods as $v) {
                $distribution = model('app\common\model\Distribution')
                    ->where(["order_no" => $order["order_no"], "type" => 2])
                    ->find();
                if (empty($distribution)) {
                    $agent_id = $user["agent_id"];
                    if (!empty($user["agent_id"])) {
                        $agent = model('app\common\model\User')->get($user["agent_id"]);
                    } else {
                        //通过上级分享购买
                        $agent = model('app\common\model\User')->get($order["agent_id"]);
                    }
                    if ($user["identity"] == 1) {
                        //如果是团队长自购
                        $agent = $user;
                        $agent_id = $user["id"];
                    }
                    if (!empty($agent)) {
                        if ($agent["identity"] != 1 && $agent["team_id"]) {
                            //如果上级绑定了团长
                            $team = model('app\common\model\User')->get($agent["team_id"]);
                            if (!empty($team) && $team["team_status"] == 1) {
                                $commiss_user_id = $agent["team_id"];
                                if ($agent["identity"] == 1 && $agent["team_status"] == 1) {
                                    $agent_id = $agent["team_id"];
                                }
                                $team_level_id = \app\common\model\team\Level::alias("level")
                                    ->field("level.goods_rebate")
                                    ->join("user user", "level.id=user.team_level_id")
                                    ->where(["user.id" => $agent["team_id"]])->find();
                                if (!empty($team_level_id)) {
                                    $rebate = $team_level_id["goods_rebate"] / 100;
                                } else {
                                    $rebate = 0.1;
                                }
                                $money = bcmul($v["actual_payment"], $rebate, 2);
                                $rebate_content = [
                                    "level_id" => $agent["team_level_id"] ?? 0,
                                    "goods_rebate" => $rebate,
                                    "money" => $money,
                                    "actual_payment" => $v["actual_payment"],
                                ];
                                $rebate_content = json_encode($rebate_content);
                                $distributionList[] = [
                                    'type' => 2,//1会员等级订单 2商品订单
                                    'order_no' => $order["order_no"],
                                    'money' => $money,//佣金
                                    'agent_id' => $agent_id,
                                    'commiss_user_id' => $commiss_user_id,//分钱用户id
                                    'identity' => 1,//分钱人身份 0分销商 1团长 2区域合伙人 4员工
                                    'user_id' => $order["user_id"],
                                    'remark' => "团队团员购买商品分佣",
                                    'rebate_content' => $rebate_content,
                                    'order_goods_id' => $v["goods_id"],
                                    'order_id' => $order["id"],
                                ];
                            }
                        } else {
                            //推荐人是员工身份 钱分给团长
                            $identity = $agent["identity"];
                            if (!empty($user["team_id"])) {
                                //如果该用户绑定了团长
                                $identity = 1;
                            }
                            $money = 0;
                            $remark = "团队团员购买商品分佣";
                            if ($agent["is_staff"] == 1 || ($agent["identity"] == 1 && $agent["team_status"] == 1)) {
                                //推荐人是员工身份 钱分给团长
                                $commiss_user_id = $agent["id"];
                                if ($agent["is_staff"] == 1) {
                                    $commiss_user_id = $agent["team_id"];
                                }
                                if ($agent["identity"] == 1 && $agent["team_status"] == 1) {
                                    $agent_id = $agent["team_id"];
                                }
                                $team_level_id = \app\common\model\team\Level::alias("level")
                                    ->field("level.goods_rebate")
                                    ->join("user user", "level.id=user.team_level_id")
                                    ->where(["user.id" => $agent["team_id"]])->find();
                                if (!empty($team_level_id)) {
                                    $rebate = $team_level_id["goods_rebate"] / 100;
                                } else {
                                    $rebate = 0.1;
                                }
                                $money = bcmul($v["actual_payment"], $rebate, 2);
                                $rebate_content = [
                                    "level_id" => $agent["team_level_id"] ?? 0,
                                    "goods_rebate" => $rebate,
                                    "money" => $money,
                                    "actual_payment" => $v["actual_payment"],
                                ];
                                $rebate_content = json_encode($rebate_content);
                                $distributionList[] = [
                                    'type' => 2,//1会员等级订单 2商品订单
                                    'order_no' => $order["order_no"],
                                    'money' => $money,//佣金
                                    'agent_id' => $agent_id,
                                    'commiss_user_id' => $commiss_user_id,//分钱用户id
                                    'identity' => $identity,//分钱人身份 0分销商 1团长 2区域合伙人 4员工
                                    'user_id' => $order["user_id"],
                                    'remark' => $remark,
                                    'rebate_content' => $rebate_content,
                                    'order_goods_id' => $v["goods_id"],
                                    'order_id' => $order["id"],
                                ];
                                //$Usermodel->commission($money,$commiss_user_id,"团员购买商品分佣",$order["id"],$order["order_no"],$identity);
                            }
                        }
                    }
                    if (!empty($user["team_id"]) && empty($agent)) {
                        $commiss_user_id = $user["team_id"];
                        //如果该用户绑定了团长
                        $identity = 1;
                        $remark = "团队团员购买商品分佣";
                        $team_level_id = \app\common\model\team\Level::alias("level")
                            ->field("level.goods_rebate")
                            ->join("user user", "level.id=user.team_level_id")
                            ->where(["user.id" => $agent["team_id"]])->find();
                        if (!empty($team_level_id)) {
                            $rebate = $team_level_id["goods_rebate"] / 100;
                        } else {
                            $rebate = 0.1;
                        }
                        $money = bcmul($v["actual_payment"], $rebate, 2);
                        $rebate_content = [
                            "level_id" => $agent["team_level_id"] ?? 0,
                            "goods_rebate" => $rebate,
                            "money" => $money,
                            "actual_payment" => $v["actual_payment"],
                        ];
                        $rebate_content = json_encode($rebate_content);
                        $distributionList[] = [
                            'type' => 2,//1会员等级订单 2商品订单
                            'order_no' => $order["order_no"],
                            'money' => $money,//佣金
                            'agent_id' => $agent_id,
                            'commiss_user_id' => $commiss_user_id,//分钱用户id
                            'identity' => $identity,//分钱人身份 0分销商 1团长 2区域合伙人 4员工
                            'user_id' => $order["user_id"],
                            'remark' => $remark,
                            'rebate_content' => $rebate_content,
                            'order_goods_id' => $v["goods_id"],
                            'order_id' => $order["id"],
                        ];
                        //$Usermodel->commission($money,$commiss_user_id,"团员购买商品分佣",$order["id"],$order["order_no"],$identity);
                    }
                    /*if((!empty($agent) &&( $agent["is_staff"] != 1 && $agent["identity"] != 1)) || empty($agent))
                    {
                        //查找区域合伙人--给区域合伙人分钱
                        $permanent=json_decode($user["permanent"],true);
                        $region=User::where(["identity"=>2,"region_status"=>1])
                            ->where('FIND_IN_SET("' . $permanent["province_id"] . '", region_address) or FIND_IN_SET("' . $permanent["city_id"] . '", region_address)  or FIND_IN_SET("' . $permanent["district_id"] . '", region_address)')
                            ->find();
                        if(!empty($region)){
                            $region_level=RegionLevel::where(["id"=>$region["region_level_id"]])->find();
                            if(!empty($region_level) && !empty($region_level["goods_rebate"])){
                                $rebate = $region_level["goods_rebate"] / 100;
                            } else {
                                $rebate = 0.15;
                            }
                            $money = bcmul($v["actual_payment"], $rebate, 2);
                            $rebate_content=[
                                "level_id"=>$region["region_level_id"]??0,
                                "rebate"=>$rebate,
                                "money"=>$money,
                                "level_money"=>$v["actual_payment"],
                            ];
                            $rebate_content=json_encode($rebate_content);
                            $distributionList[] = [
                                'type' => 2,//1会员等级订单 2商品订单
                                'order_no' => $order["order_no"],
                                'money' => $money,//佣金
                                'agent_id' => $agent["id"]??0,
                                'commiss_user_id' => $region["id"],//分钱用户id
                                'identity' => 2,//分钱人身份 0分销商 1团长 2区域合伙人 4员工
                                'user_id' => $order["user_id"],
                                'level_id' => 0,
                                'remark' => "区域下用户购买商品分佣",
                                'rebate_content' => $rebate_content,
                                'order_id' => $order["id"],
                            ];
                            //$Usermodel->commission($money,$region["id"],"区域下用户购买商品分佣",$order["id"],$order["order_no"],$identity);
                        }
                    }*/
                    //查找区域合伙人--给区域合伙人分钱 start
                    $permanent = json_decode($user["permanent"], true);
                    $region = User::where(["identity" => 2, "region_status" => 1])
                        ->where('FIND_IN_SET("' . $permanent["province_id"] . '", region_address) or FIND_IN_SET("' . $permanent["city_id"] . '", region_address)  or FIND_IN_SET("' . $permanent["district_id"] . '", region_address)')
                        ->find();
                    if (!empty($region)) {
                        $region_level = RegionLevel::where(["id" => $region["region_level_id"]])->find();
                        if (!empty($region_level) && !empty($region_level["goods_rebate"])) {
                            $rebate = $region_level["goods_rebate"] / 100;
                        } else {
                            $rebate = 0.1;
                        }
                        $money = bcmul($v["actual_payment"], $rebate, 2);
                        $rebate_content = [
                            "level_id" => $region["region_level_id"] ?? 0,
                            "rebate" => $rebate,
                            "money" => $money,
                            "level_money" => $v["actual_payment"],
                        ];
                        $rebate_content = json_encode($rebate_content);
                        $distributionList[] = [
                            'type' => 2,//1会员等级订单 2商品订单
                            'order_no' => $order["order_no"],
                            'money' => $money,//佣金
                            'agent_id' => $agent["id"] ?? 0,
                            'commiss_user_id' => $region["id"],//分钱用户id
                            'identity' => 2,//分钱人身份 0分销商 1团长 2区域合伙人 4员工
                            'user_id' => $order["user_id"],
                            'level_id' => 0,
                            'remark' => "区域下用户购买商品分佣",
                            'rebate_content' => $rebate_content,
                            'order_id' => $order["id"],
                        ];
                        //$Usermodel->commission($money,$region["id"],"区域下用户购买商品分佣",$order["id"],$order["order_no"],$identity);
                    }
                    //查找区域合伙人--给区域合伙人分钱 end
                }
            }
            if (!empty($distributionList)) {
                model('app\common\model\Distribution')->saveAll($distributionList);//分销订单数据记录
            }
            return true;
        } else {
            return ['code' => 500, 'msg' => '失败'];
        }
    }

}